<?php
/***
* @version $Id: functions_sessions.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2005 - 2006 Prent < prent@milkohol.net >
*            (c) 2004 - 2006 addit, Chris Russell, Raimon <Raimon@phpBBservice.nl> htp://phpBBservice.nl
*            (c) 2005              Merlin Sythove < Merlin@silvercircle.org >
*            (c) 2005              markus_petrux < phpbb.mods@phpmix.com > (Markus) http://www.phpmix.com
*            (c) 2004 - 2005 CyberAlien <no@public_email> (Vjacheslav Trushkin) http://www.phpbbstyles.com
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if ( !defined('IN_R3BORN') )
{
	die('Hacking attempt');
}

//
// Adds/updates a new session to the database for the given userid.
// Returns the new session ID on success.
//
function session_begin($user_id, $user_ip, $page_id, $auto_create = 0, $enable_autologin = 0, $admin = 0)
{
	global $db, $config;
	global $SID;

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	if ( isset($_COOKIE[$cookiename . '_sid']) || isset($_COOKIE[$cookiename . '_data']) )
	{
		$session_id = isset($_COOKIE[$cookiename . '_sid']) ? $_COOKIE[$cookiename . '_sid'] : '';
		$sessiondata = isset($_COOKIE[$cookiename . '_data']) ? unserialize(stripslashes($_COOKIE[$cookiename . '_data'])) : array();
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = ( isset($_GET['sid']) ) ? $_GET['sid'] : '';
		$sessionmethod = SESSION_METHOD_GET;
	}

	//
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		$session_id = '';
	}

	$page_id = (int) $page_id;

	$last_visit = 0;
	$current_time = time();
	$browser = '';

	if ( isset($_SERVER['HTTP_USER_AGENT']) && !empty($_SERVER['HTTP_USER_AGENT']) )
	{
		$browser = strtolower(substr(trim($_SERVER['HTTP_USER_AGENT']), 0, 149));
	}
	elseif ( isset($_ENV['HTTP_USER_AGENT']) && !empty($_ENV['HTTP_USER_AGENT']) )
	{
		$browser = strtolower(substr(trim($_ENV['HTTP_USER_AGENT']), 0, 149));
	}

	//
	// Are auto-logins allowed?
	// If allow_autologin is not set or is true then they are
	// (same behaviour as old session code)
	//
	if (isset($config['allow_autologin']) && !$config['allow_autologin'])
	{
		$enable_autologin = $sessiondata['autologinid'] = false;
	}

	//
	// First off attempt to join with the autologin value if we have one
	// If not, just use the user_id value
	//
	$userdata = array();

	if ($user_id != ANONYMOUS)
	{
		if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
		{
			$sql = 'SELECT u.*
				FROM ' . USERS_TABLE . ' u, ' . SESSIONS_KEYS_TABLE . ' k
				WHERE u.user_id = ' . (int) $user_id . "
					AND u.user_active = 1
					AND k.user_id = u.user_id
					AND k.key_id = '" . md5($sessiondata['autologinid']) . "'";
			if (!($result = $db->sql_query($sql)))
			{
				message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}

			$userdata = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			$enable_autologin = $login = 1;
		}
		else if (!$auto_create)
		{
			$sessiondata['autologinid'] = '';
			$sessiondata['userid'] = $user_id;

			$sql = 'SELECT *
				FROM ' . USERS_TABLE . '
				WHERE user_id = ' . (int) $user_id . '
					AND user_active = 1';
			if (!($result = $db->sql_query($sql)))
			{
				message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}

			$userdata = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			$login = 1;
		}
	}

	//
	// At this point either $userdata should be populated or
	// one of the below is true
	// * Key didn't match one in the DB
	// * User does not exist
	// * User is inactive
	//
	if (!sizeof($userdata) || !is_array($userdata) || !$userdata)
	{
		$sessiondata['autologinid'] = '';
		$sessiondata['userid'] = $user_id = ANONYMOUS;
		$enable_autologin = $login = 0;

		$sql = 'SELECT *
			FROM ' . USERS_TABLE . '
			WHERE user_id = ' . (int) $user_id;
		if (!($result = $db->sql_query($sql)))
		{
			message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
	}

### R3-born - ADD (Site disabled excluding Admins)
#
	//
	// Show 'Board is disabled' message if needed.
	//
	if( $config['board_disable'] && !defined("IN_ADMIN") && !defined("IN_LOGIN") && !defined("HAS_DIED") && ($userdata['user_level'] != ADMIN) )
	{
		$message = $config['board_disable_text'] ? $config['board_disable_text'] : 'Board_disable';
		message_die(GENERAL_MESSAGE, $message, $config['board_disable_caption']);
	}
#
### R3-born - END ADD

	//
	// Initial ban check against user id, IP and email address
	//
	preg_match('/(..)(..)(..)(..)/', $user_ip, $user_ip_parts);

### R3-born - CHANGE (Cookie Based Banning)
#
/*
	$sql = "SELECT ban_ip, ban_userid, ban_email
		FROM " . BANLIST_TABLE . "
		WHERE ban_ip IN ('" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . $user_ip_parts[4] . "', '" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . "ff', '" . $user_ip_parts[1] . $user_ip_parts[2] . "ffff', '" . $user_ip_parts[1] . "ffffff')
			OR ban_userid = $user_id";
	if ( $user_id != ANONYMOUS )
	{
		$sql .= " OR ban_email LIKE '" . str_replace("\'", "''", $userdata['user_email']) . "'
			OR ban_email LIKE '" . substr(str_replace("\'", "''", $userdata['user_email']), strpos(str_replace("\'", "''", $userdata['user_email']), "@")) . "'";
	}
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
	}

	if ( $ban_info = $db->sql_fetchrow($result) )
	{
		if ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] )
		{
			message_die(CRITICAL_MESSAGE, 'You_been_banned');
		}
	}
*/

  //Give banned users a cookie and check that too, in addition to the existing checks.
  //Once the cookie is in place: if it matches the database, the user is banned,
  //even if the user gets another IP or is not logged in so the user ID is unknown.

  //Get cookie ban settings.
  $ban_cookie = '';
  $banned_id = isset($_COOKIE[$config['cookie_name'].'_banned_id']) ? $_COOKIE[$config['cookie_name'].'_banned_id'] : '';
  $banned_ip = isset($_COOKIE[$config['cookie_name'].'_banned_ip']) ? $_COOKIE[$config['cookie_name'].'_banned_ip'] : '';

  //Yes, cookie ban settings were there. See if they match the database.
  //If not, delete cookie.
  if ($banned_ip || $banned_id)
  {
    $sql = "SELECT * FROM " . BANLIST_TABLE . " WHERE ";
      $sql .= ($banned_ip) ? " ban_ip = '" . $banned_ip . "'" : '';
      $sql .= ($banned_id) ? ($banned_ip ? ' OR ' : '') . ' ban_userid = ' . $banned_id : '';
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
	}
	if ( $ban_info = $db->sql_fetchrow($result) )
    {
		$ban_cookie =  ( $ban_info['ban_ip'] || $ban_info['ban_userid']);
	}
    //There was a cookie but no match in the database, so the ban is lifted:
    //delete the cookie by setting the expiry time 1 hour (3600 = 1 Hour) ago
    if (! $ban_cookie)
    {
		if ($banned_ip)
		{
			setcookie($config['cookie_name'].'_banned_ip',$banned_ip, time()-3600);
		}
		if ($banned_id)
		{
			setcookie($config['cookie_name'].'_banned_id',$banned_id, time()-3600);
		}
     }
  }
  //Have $ban_cookie, if not empty, the user is banned via a cookie.
  //If empty, then there was no cookie, or there was no LONGER a database match so the cookie was deleted

  //Check if there is database ban info - this is roughly the original ban code
  $ban_database = '';
  $sql = "SELECT *
      FROM " . BANLIST_TABLE . "
      WHERE ban_ip IN ('" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . $user_ip_parts[4] . "', '" . $user_ip_parts[1] . $user_ip_parts[2] . $user_ip_parts[3] . "ff', '" . $user_ip_parts[1] . $user_ip_parts[2] . "ffff', '" . $user_ip_parts[1] . "ffffff')
         OR ban_userid = $user_id";
	if ( $user_id != ANONYMOUS )
   	{
    	$sql .= " OR ban_email LIKE '" . str_replace("\'", "''", $userdata['user_email']) . "'
        	OR ban_email LIKE '" . substr(str_replace("\'", "''", $userdata['user_email']), strpos(str_replace("\'", "''", $userdata['user_email']), "@")) . "'";
   	}
   	if ( !($result = $db->sql_query($sql)) )
   	{
    	message_die(CRITICAL_ERROR, 'Could not obtain ban information', '', __LINE__, __FILE__, $sql);
   	}

   	if ( $ban_info = $db->sql_fetchrow($result) )
	{
    	$ban_database = ( $ban_info['ban_ip'] || $ban_info['ban_userid'] || $ban_info['ban_email'] );
	    //Fill these variables from database if not filled from cookie yet
    	if (! $banned_ip){
			$banned_ip = $ban_info['ban_ip'];
    	}
    	if (! $banned_id) {
			$banned_id = $ban_info['ban_userid'];
    	}
  	}

  	//User is banned in some way?
  	if ($ban_cookie || $ban_database)
  	{
    	//Set the ban_cookie, time it for 1 year (365*24*3600 = 31536000 = 1 Year). The time restarts every time the user comes here
    	if ($banned_ip)
    	{
    		setcookie($config['cookie_name'].'_banned_ip',$banned_ip, time()+31536000);
    	}
    	if ($banned_id)
    	{
    		setcookie($config['cookie_name'].'_banned_id',$banned_id, time()+31536000);
    	}
     	//Close the forum to this person
    	message_die(CRITICAL_MESSAGE, 'You_been_banned');
  	}
#
### R3-born - END CHANGE

	//
	// Create or update the session
	//

### R3-born - CHANGE (Guest Sessions)
#
/*
	$sql = "UPDATE " . SESSIONS_TABLE . "
		SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = $page_id, session_logged_in = $login, session_admin = $admin
		WHERE session_id = '" . $session_id . "'
			AND session_ip = '$user_ip'";
*/
	$sql_ip = $user_id == ANONYMOUS ? " AND session_ip = '$user_ip'" : '';
	$sql = "UPDATE " . SESSIONS_TABLE . "
		SET session_ip = '$user_ip', session_start = $current_time, session_time = $current_time, session_page = $page_id, session_logged_in = $login, session_browser = '$browser', session_admin = $admin
		WHERE session_id = '" . $session_id . "' $sql_ip
			AND session_user_id = '$user_id'";
#
### R3-born - END CHANGE

	if ( !$db->sql_query($sql) || !$db->sql_affectedrows() )
	{
		$session_id = md5(dss_rand());

		$sql = "INSERT INTO " . SESSIONS_TABLE . "
			(session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_browser, session_admin)
			VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', $page_id, $login, '$browser', $admin)";
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
		}
	}

	if ( $user_id != ANONYMOUS )
	{
		$last_visit = ( $userdata['user_session_time'] > 0 ) ? $userdata['user_session_time'] : $current_time;

		if (!$admin)
		{
			$sql = "UPDATE " . USERS_TABLE . "
				SET user_session_time = $current_time, user_session_page = $page_id, user_lastvisit = $last_visit
				WHERE user_id = $user_id";
			if ( !$db->sql_query($sql) )
			{
				message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
			}
		}

		$userdata['user_lastvisit'] = $last_visit;

		//
		// Regenerate the auto-login key
		//
		if ($enable_autologin)
		{
			$auto_login_key = dss_rand() . dss_rand();

			if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
			{
				$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
					SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
					WHERE key_id = '" . md5($sessiondata['autologinid']) . "'";
			}
			else
			{
				$sql = 'INSERT INTO ' . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login)
					VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
			}

			if ( !$db->sql_query($sql) )
			{
				message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
			}

			$sessiondata['autologinid'] = $auto_login_key;
			unset($auto_login_key);
		}
		else
		{
			$sessiondata['autologinid'] = '';
		}

//		$sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
		$sessiondata['userid'] = $user_id;
	}

	$userdata['session_id'] = $session_id;
	$userdata['session_ip'] = $user_ip;
	$userdata['session_browser'] = $browser;
	$userdata['session_user_id'] = $user_id;
	$userdata['session_logged_in'] = $login;
	$userdata['session_page'] = $page_id;
	$userdata['session_start'] = $current_time;
	$userdata['session_time'] = $current_time;
	$userdata['session_admin'] = $admin;
	$userdata['session_key'] = $sessiondata['autologinid'];

	setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);

### R3-born - CHANGE (Guest Sessions)
#
//	$SID = 'sid=' . $session_id;
    $SID = $user_id > 0 ? 'sid=' . $session_id : '';
#
### R3-born - END CHANGE

	return $userdata;
}

//
// Checks for a given user session, tidies session table and updates user
// sessions at each page refresh
//
function session_pagestart($user_ip, $thispage_id)
{
	global $db, $lang, $config;
	global $SID;

### R3-born - ADD (Module Engine)
#
	global $mvModuleName, $mvPages, $mvModules;

	//Set the page ID depending on if we are a module or in the core.
	if (!defined('IN_ADMIN') && $mvModuleName != '' && $mvModules[$mvModuleName]['type'] == ADDON_MODULE)
	{
		// Surpress any potential warnings when the site is disabled
		$thispage_id = ($config['board_disable']) ? @constant('MODULE_' . $mvModuleName . '_'	. $thispage_id) : constant('MODULE_' . $mvModuleName . '_'	. $thispage_id);
	}
	else
	{
		// Surpress any potential warnings when the site is disabled
		$thispage_id = ($config['board_disable']) ? @constant('CORE_' . $thispage_id) : constant('CORE_' . $thispage_id);
	}
#
### R3-born - END

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	$current_time = time();
	$userdata = array();

	if ( isset($_COOKIE[$cookiename . '_sid']) || isset($_COOKIE[$cookiename . '_data']) )
	{
		$sessiondata = isset( $_COOKIE[$cookiename . '_data'] ) ? unserialize(stripslashes($_COOKIE[$cookiename . '_data'])) : array();
		$session_id = isset( $_COOKIE[$cookiename . '_sid'] ) ? $_COOKIE[$cookiename . '_sid'] : '';
		$sessionmethod = SESSION_METHOD_COOKIE;
	}
	else
	{
		$sessiondata = array();
		$session_id = ( isset($_GET['sid']) ) ? $_GET['sid'] : '';
		$sessionmethod = SESSION_METHOD_GET;
	}

	//
	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		$session_id = '';
	}

	$thispage_id = (int) $thispage_id;

	//
	// Does a session exist?
	//
	if ( !empty($session_id) )
	{
		//
		// session_id exists so go ahead and attempt to grab all
		// data in preparation
		//
		$sql = "SELECT u.*, s.*
			FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u
			WHERE s.session_id = '$session_id'
				AND u.user_id = s.session_user_id";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);

### R3-born - ADD (Site disabled excluding Admins)
#
		//
		// Show 'Board is disabled' message if needed, if not in admin panel, if not logging in,
		// if message_die() hasn't been called yet, and if user is not an admin
		//
		if( $config['board_disable'] && !defined("IN_ADMIN") && !defined("IN_LOGIN") && !defined("HAS_DIED") && ($userdata['user_level'] != ADMIN) )
		{
			$message = $config['board_disable_text'] ? $config['board_disable_text'] : 'Board_disable';
			message_die(GENERAL_MESSAGE, $message, $config['board_disable_caption']);
		}
#
### R3-born - END ADD

		//
		// Did the session exist in the DB?
		//
		if ( isset($userdata['user_id']) )
		{
			//
			// Do not check IP assuming equivalence, if IPv4 we'll check only first 24
			// bits ... I've been told (by vHiker) this should alleviate problems with
			// load balanced et al proxies while retaining some reliance on IP security.
			//
			$ip_check_s = substr($userdata['session_ip'], 0, 6);
			$ip_check_u = substr($user_ip, 0, 6);

			if ($ip_check_s == $ip_check_u)
			{
### R3-born - CHANGE (Guest Sessions)
#
//				$SID = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
				$SID = $userdata['user_id'] > 0 ? (($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '') : '';
#
### R3-born - END CHANGE
				//
				// Only update session DB a minute or so after last update OR...
				// ...when user changes to another page (so we get up to date info for viewonline)
				//
### R3-born - CHANGE (Updated Sessions)
#
				//if ( $current_time - $userdata['session_time'] > 60 )
				if ( $current_time - $userdata['session_time'] > 60 || $thispage_id != $userdata['session_page'] )
				{
					$userdata['session_page'] = $thispage_id;
#
### R3-born - END CHANGE
					// A little trick to reset session_admin on session re-usage
					$update_admin = (!defined('IN_ADMIN') && $current_time - $userdata['session_time'] > ($config['session_length']+60)) ? ', session_admin = 0' : '';

					$sql = "UPDATE " . SESSIONS_TABLE . "
						SET session_time = $current_time, session_page = $thispage_id $update_admin
						WHERE session_id = '" . $userdata['session_id'] . "'";
					if ( !$db->sql_query($sql) )
					{
						message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
					}

					if ( $userdata['user_id'] != ANONYMOUS )
					{
						$sql = "UPDATE " . USERS_TABLE . "
							SET user_session_time = $current_time, user_session_page = $thispage_id
							WHERE user_id = " . $userdata['user_id'];
						if ( !$db->sql_query($sql) )
						{
							message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
						}
					}

					session_clean($userdata['session_id']);

					setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
					setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
				}

				// Add the session_key to the userdata array if it is set
				if ( isset($sessiondata['autologinid']) && $sessiondata['autologinid'] != '' )
				{
					$userdata['session_key'] = $sessiondata['autologinid'];
				}

				return $userdata;
			}
		}
	}
### R3-born - ADD (Guest Sessions)
#
	elseif(empty($sessiondata))
	{

		// try to login guest
		$sql = "SELECT u.*, s.*
			FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u
			WHERE s.session_ip = '$user_ip'
				AND s.session_user_id = " . ANONYMOUS . "
				AND u.user_id = s.session_user_id
					LIMIT 0, 1";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
		}

		$userdata = $db->sql_fetchrow($result);

		//
		// Show 'Board is disabled' message if needed, if not in admin panel, if not logging in,
		// if message_die() hasn't been called yet, and if user is not an admin
		//
		if( $config['board_disable'] && !defined("IN_ADMIN") && !defined("IN_LOGIN") && !defined("HAS_DIED") && ($userdata['user_level'] != ADMIN) )
		{
			$message = $config['board_disable_text'] ? $config['board_disable_text'] : 'Board_disable';
			message_die(GENERAL_MESSAGE, $message, $config['board_disable_caption']);
		}


		if ( isset($userdata['user_id']) )
		{
			if ( $current_time - $userdata['session_time'] > 60 )
			{
				$sql = "UPDATE " . SESSIONS_TABLE . "
					SET session_time = $current_time, session_start = $current_time, session_page = 0
					WHERE session_id = '" . $userdata['session_id'] . "'";
				if ( !$db->sql_query($sql) )
				{
					message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
				}
			}
			return $userdata;
		}
	}
#
### R3-born - END ADD

	//
	// If we reach here then no (valid) session exists. So we'll create a new one,
	// using the cookie user_id if available to pull basic user prefs.
	//
	$user_id = ( isset($sessiondata['userid']) ) ? intval($sessiondata['userid']) : ANONYMOUS;

	if ( !($userdata = session_begin($user_id, $user_ip, $thispage_id, TRUE)) )
	{
		message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
	}

	return $userdata;

}

/**
* Terminates the specified session
* It will delete the entry in the sessions table for this session,
* remove the corresponding auto-login key and reset the cookies
*/
function session_end($session_id, $user_id)
{
	global $db, $lang, $config, $userdata;
	global $SID;

	$cookiename = $config['cookie_name'];
	$cookiepath = $config['cookie_path'];
	$cookiedomain = $config['cookie_domain'];
	$cookiesecure = $config['cookie_secure'];

	$current_time = time();

	if (!preg_match('/^[A-Za-z0-9]*$/', $session_id))
	{
		return;
	}

	//
	// Delete existing session
	//
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
		WHERE session_id = '$session_id'
			AND session_user_id = $user_id";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
	}

	//
	// Remove this auto-login entry (if applicable)
	//
	if ( isset($userdata['session_key']) && $userdata['session_key'] != '' )
	{
		$autologin_key = md5($userdata['session_key']);
		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
			WHERE user_id = ' . (int) $user_id . "
				AND key_id = '$autologin_key'";
		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
		}
	}

	//
	// We expect that message_die will be called after this function,
	// but just in case it isn't, reset $userdata to the details for a guest
	//
	$sql = 'SELECT *
		FROM ' . USERS_TABLE . '
		WHERE user_id = ' . ANONYMOUS;
	if ( !($result = $db->sql_query($sql)) )
	{
		message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
	}
	if ( !($userdata = $db->sql_fetchrow($result)) )
	{
		message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
	}
	$db->sql_freeresult($result);


	setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
	setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);

	return true;
}

/**
* Removes expired sessions and auto-login keys from the database
*/
function session_clean($session_id)
{
	global $config, $db;

	//
	// Delete expired sessions
	//
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . '
		WHERE session_time < ' . (time() - (int) $config['session_length']) . "
			AND session_id <> '$session_id'";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
	}

	//
	// Delete expired auto-login keys
	// If max_autologin_time is not set then keys will never be deleted
	// (same behaviour as session code)
	//
	if (!empty($config['max_autologin_time']) && $config['max_autologin_time'] > 0)
	{
		$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
			WHERE last_login < ' . (time() - (86400 * (int) $config['max_autologin_time']));
		$db->sql_query($sql);
	}

	return true;
}

/**
* Reset all login keys for the specified user
* Called on password changes
*/
function session_reset_keys($user_id, $user_ip)
{
	global $db, $userdata, $config;

	$key_sql = ($user_id == $userdata['user_id'] && !empty($userdata['session_key'])) ? "AND key_id != '" . md5($userdata['session_key']) . "'" : '';

	$sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . '
		WHERE user_id = ' . (int) $user_id . "
			$key_sql";

	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
	}

	$where_sql = 'session_user_id = ' . (int) $user_id;
	$where_sql .= ($user_id == $userdata['user_id']) ? " AND session_id <> '" . $userdata['session_id'] . "'" : '';
	$sql = 'DELETE FROM ' . SESSIONS_TABLE . "
		WHERE $where_sql";
	if ( !$db->sql_query($sql) )
	{
		message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
	}

	if ( !empty($key_sql) )
	{
		$auto_login_key = dss_rand() . dss_rand();

		$current_time = time();

		$sql = 'UPDATE ' . SESSIONS_KEYS_TABLE . "
			SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time
			WHERE key_id = '" . md5($userdata['session_key']) . "'";

		if ( !$db->sql_query($sql) )
		{
			message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
		}

		// And now rebuild the cookie
		$sessiondata['userid'] = $user_id;
		$sessiondata['autologinid'] = $auto_login_key;
		$cookiename = $config['cookie_name'];
		$cookiepath = $config['cookie_path'];
		$cookiedomain = $config['cookie_domain'];
		$cookiesecure = $config['cookie_secure'];

		setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);

		$userdata['session_key'] = $auto_login_key;
		unset($sessiondata);
		unset($auto_login_key);
	}
}

//
// Append $SID to a url. Borrowed from phplib and modified. This is an
// extra routine utilised by the session code above and acts as a wrapper
// around every single URL and form action. If you replace the session
// code you must include this routine, even if it's empty.
//
//$url = STRING - the url
//$non_html_amp = BOOLEAN - true or false - if true all will replace all &amp; with & which is required if the URL is being used as a parameter for a redirect, etc.
//$force_module = STRING - any module name - if other than '' will force append_sid to look for url matches in the given module name.
function append_sid($url, $non_html_amp = false, $force_module = '')
{
	global $SID;

### R3-born - ADD
#
	global $root_path, $mvModules, $mvModuleName, $phpEx;

	$mvModuleSearch = ($force_module != '') ? $force_module : $mvModuleName;

	$matches = array();
	if (preg_match("~((admin)?[^\/\?&]*)\.$phpEx(?:[\?&]([^<>\s]*))?$~i", $url, $matches))
	{
		// $matches[1] = "admin_file"
		// $matches[2] = "admin"
		// $matches[3] = "mode=view&f=5"
		//if (!empty($matches[2])) //	Admin
		if ( isset($matches[2]) && !empty($matches[2]) ) // Admin
		{
			foreach	($mvModules as $name =>	$value)
			{
				if ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT)
				{
					if (in_array("$matches[1].$phpEx", $value['admin']))
					{
						$url = $root_path . "admin/index.$phpEx?module=$name&file=$matches[1]" . ($matches[3]	? "&$matches[3]" : '');
						break;
					}
				}
			}
		}
		else if	($mvModuleSearch != '' && in_array("$matches[1].$phpEx", $mvModules[$mvModuleSearch]['files']))
		{
			//$url = "index.$phpEx?module=$mvModuleName$ampfile=$matches[1]"	. (!empty($matches[3]) ? "$amp$matches[3]"	: '');
			$url = 'index.' . $phpEx . '?module=' . $mvModuleSearch . '&amp;file=' . $matches[1] . (!empty($matches[3]) ? '&amp;' . $matches[3] : '');
		}
	}

	//Change instances of &amp; to &
	if ($non_html_amp)
	{
		$new_url = str_replace('&amp;', '&', $url);
		$url = $new_url;
	}
#
### R3-born - END ADD

	if ( !empty($SID) && !preg_match('#sid=#', $url) )
	{
		$url .= ( ( strpos($url, '?') !== false ) ? ( ( $non_html_amp ) ? '&' : '&amp;' ) : '?' ) . $SID;
	}

	return $url;
}

// Automatically assign page id for session handling and layout management.
function register_page_id($page_id, $page_url, $page_name, $core_page = false)
{
    global $mvModuleName, $mvPages, $mvLayouts, $phpEx;

	if ($core_page)
	{
		// This is a core page.
		define('CORE_' . $page_id, count($mvPages));
		define($page_id, $page_id);

		$page_data = array('id' => count($mvPages), 'url' => $page_url, 'name' => $page_name);
		$mvPages[] = $page_data;

		$layout_url = $page_url;
		$layout_name = 'Core - ' . $page_url;

		if (!isset($mvLayouts[$layout_url]))
		{
			//update $mvLayouts, used by the layout manager to determine what layout to use for a given page.
			$layout_data = array('name' => $layout_name, 'module_id' => 0);
			$mvLayouts[$layout_url] = $layout_data;
		}

		return true;
	}
    elseif ($mvModuleName != '')
    {
		//The url we adding to the layouts below to a module.
		define('MODULE_' . $mvModuleName . '_' . $page_id, count($mvPages));
		define($page_id, $page_id);

		// Update $mvPages - used to determine what page a user is currently browsing.
		$page_data = array('id' => count($mvPages), 'url' => buildModuleURL($mvModuleName, $page_url), 'name' => $page_name);
		$mvPages[] = $page_data;

		$layout_url = buildModuleURL($mvModuleName, str_replace('.'.$phpEx, '', $page_url));
		$layout_name = getModuleDisplayName($mvModuleName) . ' - ' . $page_url;
		$module_id = getModuleID($mvModuleName);

		if (!isset($mvLayouts[$layout_url]))
		{
			//update $mvLayouts, used by the layout manager to determine what layout to use for a given page.
			$layout_data = array('name' => $layout_name, 'module_id' => $module_id);
			$mvLayouts[$layout_url] = $layout_data;
		}

		return true;
    }
	else
	{
		return false;
	}
}

?>